package com.fuyao.cloud.admin.flow.actor;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.fuyao.cloud.flowable.entity.ActorUser;
import com.fuyao.cloud.admin.api.entity.SysUser;
import com.fuyao.cloud.flowable.vo.ActorInstance;
import com.fuyao.cloud.admin.api.vo.UserRoleVO;
import com.fuyao.cloud.admin.service.SysRoleService;
import com.fuyao.cloud.admin.service.SysUserService;
import com.fuyao.cloud.common.security.service.CloudUser;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.compress.utils.Lists;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 定义角色-规则，用于获取指定角色所关联的用户信息
 * 例：指定角色编码 BMLD_GROUP 则会加载 这个角色所关联的所有用户信息
 *
 * @author lyhill
 * @version 1.0
 * @date 2022年11月18日
 */
@Slf4j
@ActorTypeCodeAnnotation("AT_ROLE")
@Component
public class ActorTypeAtRole implements ActorTypeFactory {

    @Autowired
    public SysRoleService roleService;

    @Autowired
    private SysUserService userService;

    @Override
    public List<ActorInstance> execute(CloudUser user, ActorUser actorUser, String procInstId) {

        log.info("AT_ROLE : actorId:{}, procInstId:{}", actorUser.getActorId(), procInstId);

        if (ObjectUtil.isEmpty(actorUser) || StrUtil.isEmpty(actorUser.getActorId())) {
            return Lists.newArrayList();
        }

        List<UserRoleVO> userRoleVOList = roleService.listRoleByRoleCode(actorUser.getParams(), -1L);
        if (CollUtil.isEmpty(userRoleVOList)) {
            return Lists.newArrayList();
        }
        List<Long> userIds = userRoleVOList.stream().map(UserRoleVO::getUserId).collect(Collectors.toList());
        List<SysUser> userList = userService.listByIds(userIds);

        List<ActorInstance> actorInstanceList = Lists.newArrayList();
        if (CollUtil.isNotEmpty(userList)) {
            userList.forEach(sysUser -> {
                ActorInstance actorInstance = new ActorInstance(sysUser);
                actorInstanceList.add(actorInstance);
            });
        }
        return actorInstanceList;
    }
}
